Imports Cdm.DataCore.Budget
Imports Cdm.DataCore.CaseNotes
Imports Cdm.DataCore.LookupTables
Partial Class Budget_SpendingPlanUpload
    Inherits System.Web.UI.Page
    Private Property ConfirmSpendingPlanFileName() As String
        Get
            If ViewState("spendingplanfilename") Is Nothing Then
                Return ""
            Else
                Return ViewState("spendingplanfilename")
            End If
        End Get
        Set(ByVal value As String)
            ViewState("spendingplanfilename") = value
        End Set
    End Property

    Private Property ConfirmSpendingPlan() As Cdm.DataCore.Budget.SpendingPlan
        Get
            If ViewState("uploadspendingplan") Is Nothing Then
                Return Nothing
            Else
                Return CType(ViewState("uploadspendingplan"), Cdm.DataCore.Budget.SpendingPlan)
            End If
        End Get
        Set(ByVal value As Cdm.DataCore.Budget.SpendingPlan)
            ViewState("uploadspendingplan") = value
        End Set
    End Property

    Private Property SortExpression() As String
        Get
            If ViewState("SortExpression") Is Nothing Then
                ViewState("SortExpression") = "DateModified"
            End If
            Return ViewState("SortExpression")
        End Get
        Set(ByVal value As String)
            If value.Equals(Me.SortExpression) Then
                ToggleSortDirection()
            Else
                ViewState("SortDirection") = " ASC"
            End If
            ViewState("SortExpression") = value
        End Set
    End Property

    Private Sub ToggleSortDirection()
        If ViewState("SortDirection").Equals(" DESC") Then
            ViewState("SortDirection") = " ASC"
        Else
            ViewState("SortDirection") = " DESC"
        End If
    End Sub

    Private ReadOnly Property SortDirection() As String
        Get
            Return ViewState("SortDirection")
        End Get
    End Property

    Protected Sub SubmitButton_Click(ByVal sender As Object, _
                                     ByVal e As System.EventArgs) _
                                     Handles SubmitButton.Click

        'First Check if a file was selected for upload.
        If String.IsNullOrEmpty(FileUploadControl.FileName) Then
            Exit Sub
        End If

        Dim spendingPlanDropLocation As String = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings.Get("SpendingPlanDrop"))
        FileUploadControl.SaveAs(spendingPlanDropLocation & FileUploadControl.FileName)
        UploadSpendingPlan(spendingPlanDropLocation & FileUploadControl.FileName, False)

    End Sub

    Private Sub UploadSpendingPlan(ByVal spendingPlanFileName As String, ByVal bAlreadyConfirmed As Boolean)
        Try

            Dim Participant As Cdm.DataCore.Entities.Participant = EntityController.GetParticipant()
            Dim spendingPlan As New Cdm.DataCore.Budget.SpendingPlan
            If bAlreadyConfirmed Then
                spendingPlan = Me.ConfirmSpendingPlan
            End If
            spendingPlan.Comments = Me.CommentsTextBox.Text

            Dim bItemServiceDropdowns As Boolean
            Try
                bItemServiceDropdowns = CBool(Application("UseDropdownsForItemAndServiceCodes"))
            Catch ex As Exception
                bItemServiceDropdowns = False
            End Try


            Dim spBuilder As New Spreadsheet.SpendingPlan()
            Dim spendingPlanName As String = EntityController.ReplaceDisplayName("Spending Plan")
            Dim caseNoteText As String

            If CommentsTextBox.Text <> "" Then
                caseNoteText = Me.CommentsTextBox.Text
            Else
                caseNoteText = "No comments entered by creator."
            End If

            Dim result As String = spBuilder.UploadSpendingPlan(spendingPlanFileName, Participant.ParticipantId, UserAuthorization.CurrentUser.LogonId(), spendingPlan, bAlreadyConfirmed, bItemServiceDropdowns)
            If result.StartsWith("Success") Then
                ResultLabel.Text = result.Replace("Spending Plan", spendingPlanName)
                ResultLabel.ForeColor = Drawing.Color.Green
                ResultLabel.Visible = True

                createCaseNote(Participant.ParticipantId, spendingPlan)

                Me.CommentsTextBox.Text = ""

            ElseIf result.StartsWith("Confirm") Then
                Me.ConfirmSpendingPlan = spendingPlan
                Me.ConfirmSpendingPlanFileName = spendingPlanFileName
                ShowConfirmMessage(result)
            Else
                ResultLabel.Text = result
                ResultLabel.ForeColor = Drawing.Color.Red
                ResultLabel.Visible = True
            End If
            If Not Participant Is Nothing Then
                EntityController.SendNotification(Cdm.DataCore.CaseNotes.Notification.NotificationType.SpendingPlanSubmittedForApproval, Participant.ParticipantId)
            End If
        Catch ex As Exception
            ResultLabel.Text = EntityController.ReplaceDisplayName("Spending Plan") + " Upload Error: " + ex.Message
            ResultLabel.ForeColor = Drawing.Color.Red
            ResultLabel.Visible = True
        End Try
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, _
                            ByVal e As System.EventArgs) _
                            Handles Me.Load

        SetupJavaScript()
        Me.ValidationErrorSummary1.Visible = False
        Dim Participant As New Cdm.DataCore.Entities.Participant()
        Participant = EntityController.GetParticipant()
        If Participant IsNot Nothing Then
            ParticipantNameLabel.Text = Participant.DisplayLastNameFirst()
        End If
        If Not Me.IsPostBack Then
            UserAuthorization.CheckPagePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseSpendingPlan, "VIEW")
            EntityController.SetSubNavTabsFinancial(Me.EditCaseSubNav)
            EntityController.SetFinancialTab(Me.FinancialSubName, Me.EditCaseSubNav)
            SpendingPlanLabel.Text = EntityController.ReplaceDisplayName("Spending Plan")
            SpendingPlanTwoLabel.Text = "Upload " + EntityController.ReplaceDisplayName("Spending Plan")
            Me.UploadSpendingPlanPanel.Visible = UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseSpendingPlan)
            'BindGrid()
        End If

        pageDiv.Visible = True

    End Sub

    Private Sub SetupJavaScript()
        EntityController.JavaScriptSetFixedHeight(0)
        EntityController.JavaScriptAddChildDiv(Me.maindiv.ClientID, 50)
        EntityController.JavaScriptAddChildDiv(Me.pageDiv.ClientID, 70)
    End Sub




    Protected Sub EditCaseSubNav2_ChangeMenu(ByVal sender As Object, _
                                             ByVal e As System.EventArgs) _
                                             Handles EditCaseSubNav.ChangeMenu

        EntityController.ReturnToCasePersonalPage(EditCaseSubNav)

    End Sub






    

    Private Sub ShowConfirmMessage(ByVal errorMessage As String)
        FormError(errorMessage)
        Me.UploadConfirmPanel.Visible = True

    End Sub

    Private Sub ShowConfirmMessage(ByVal errorMessage As String, ByVal bSpendingPlanDenied As Boolean, _
                                ByVal oldStartDate As DateTime, ByVal oldEndDate As DateTime, ByVal oldStatusId As Integer)



        ShowConfirmMessage(errorMessage)
        'Add the old values to the ViewState for retrieval on confirm, to determine
        'what notifications need to be sent.
        ViewState("oldStartDate") = oldStartDate
        ViewState("oldEndDate") = oldEndDate
        ViewState("oldStatusId") = oldStatusId

    End Sub


    ''' <summary>
    ''' From the changed information, check to see what notifications need to
    ''' be sent out.
    ''' </summary>
    ''' <param name="oldStartDate">Start date before update</param>
    ''' <param name="oldEndDate">End date before update</param>
    ''' <param name="oldStatusId">Status before update</param>
    ''' <param name="newStartDate">start date after update</param>
    ''' <param name="newEndDate">end date after update</param>
    ''' <param name="newStatusId">Status after update</param>
    ''' <remarks></remarks>
    Private Sub SendNotifications(ByVal oldStartDate As DateTime, ByVal oldEndDate As DateTime, ByVal oldStatusId As Integer, _
                                  ByVal newStartDate As DateTime, ByVal newEndDate As DateTime, ByVal newStatusId As Integer)

        Dim participantId As Integer = EntityController.GetParticipant().ParticipantId
        'Check if the status has changed
        'If the status is changned to:  approve, send a Spendingplanapproved notification
        '                               Denied - then send a SpendingPlanRejected notification
        '                               Submitted - then send a SpendingPlanSubmittedForApproval
        If oldStatusId <> newStatusId Then
            If newStatusId = LuSpendingPlanStatus.SpendingPlanStatus.Approved Then
                EntityController.SendNotification(Notification.NotificationType.SpendingPlanApproved, participantId)
            End If
            If newStatusId = LuSpendingPlanStatus.SpendingPlanStatus.Denied Then
                EntityController.SendNotification(Notification.NotificationType.SpendingPlanRejected, participantId)
            End If

            If newStatusId = LuSpendingPlanStatus.SpendingPlanStatus.Submitted Then
                EntityController.SendNotification(Notification.NotificationType.SpendingPlanSubmittedForApproval, participantId)
            End If
        End If

        'If the startdate or enddate has changed, and the spending plan was previously approved,
        'then send the previousapproved spending plan has had dates changed notification
        If (Not oldStartDate.ToShortDateString().Equals(newStartDate.ToShortDateString())) Or _
           (Not oldEndDate.ToShortDateString().Equals(newEndDate.ToShortDateString())) Then
            If oldStatusId = LuSpendingPlanStatus.SpendingPlanStatus.Approved Then
                EntityController.SendNotification(Notification.NotificationType.SpendingPlanPreviouslyApprovedHasDatesChanges, participantId)
            End If
        End If

    End Sub

    
    Private Sub FormError(ByVal errorMessage As String)
        Me.ValidationErrorSummary1.SetSingleError(errorMessage)
        Me.ValidationErrorSummary1.Visible = True
    End Sub

    Protected Sub CancelUploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CancelUploadButton.Click
        Me.ConfirmSpendingPlan = Nothing
        Me.ConfirmSpendingPlanFileName = Nothing
        Me.UploadConfirmPanel.Visible = False
    End Sub

    Protected Sub ConfirmUploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ConfirmUploadButton.Click
        Try

            If Not String.IsNullOrEmpty(Me.ConfirmSpendingPlanFileName) Then
                UploadSpendingPlan(Me.ConfirmSpendingPlanFileName, True)
            Else
                'This section is for confirming updates
                'If Me.ConfirmSpendingPlan.SpendingPlanStatusId = Cdm.DataCore.LookupTables.LuSpendingPlanStatus.SpendingPlanStatus.Denied Then
                ' Me.ConfirmSpendingPlan.DenialReasonId = CInt(DenialReasonDropDownList.SelectedValue)
                'End If
                ConfirmSpendingPlan.Comments = CommentsTextBox.Text
                ConfirmSpendingPlan.Persist()
                createCaseNote(EntityController.GetParticipant().ParticipantId, ConfirmSpendingPlan)
            End If

            CommentsTextBox.Text = ""

            Dim oldStartDate As DateTime
            If ViewState("oldStartDate") Is Nothing Then
                oldStartDate = ConfirmSpendingPlan.StartDate
            Else
                oldStartDate = CDate(ViewState("oldStartDate"))
            End If
            Dim oldEndDate As DateTime
            If ViewState("oldEndDate") Is Nothing Then
                oldEndDate = ConfirmSpendingPlan.StartDate
            Else
                oldEndDate = CDate(ViewState("oldEndDate"))
            End If
            Dim oldStatusId As Integer
            If ViewState("oldStatusId") Is Nothing Then
                oldStatusId = 0
            Else
                oldStatusId = CInt(ViewState("oldStatusId"))
            End If

            SendNotifications(oldStartDate, oldEndDate, oldStatusId, _
                           ConfirmSpendingPlan.StartDate, ConfirmSpendingPlan.EndDate, _
                           ConfirmSpendingPlan.SpendingPlanStatusId)

            'If ConfirmSpendingPlan.SpendingPlanStatusId = Cdm.DataCore.LookupTables.LuSpendingPlanStatus.SpendingPlanStatus.Denied Then
            'Response.Redirect("~/Case/CasePersonal.aspx?ActiveTab=Notes&spendingplandenyreason=" & Me.DenialReasonDropDownList.SelectedValue)
            'End If


            Me.ConfirmSpendingPlan = Nothing
            Me.ConfirmSpendingPlanFileName = Nothing
            Me.UploadConfirmPanel.Visible = False
        Catch ex As Exception
            FormError(ex.Message)
        End Try

    End Sub


    Private Sub createCaseNote(ByVal participantId As Integer, ByRef spendingPlan As Cdm.DataCore.Budget.SpendingPlan)
        Dim tran As New Gentle.Framework.Transaction
        Dim caseNote As New Cdm.DataCore.CaseNotes.CaseNote

        caseNote.ParticipantId = participantId
        caseNote.AttachmentFileName = Nothing
        caseNote.LastModified = DateTime.Now.ToString()
        caseNote.DateModified = DateTime.Now
        caseNote.Subject = "Spending Plan " + spendingPlan.StartDate.ToString() + " to " + spendingPlan.EndDate.ToString() _
                        + " " + spendingPlan.Version.ToString()
        caseNote.AuthorUserId = UserAuthorization.CurrentUser.UserId
        caseNote.CaseNoteTypeId = 17008
        caseNote.CaseNoteStatusId = 1
        caseNote.CaseNoteResolutionId = 1
        caseNote.RefId = spendingPlan.SpendingPlanId

        If CommentsTextBox.Text <> "" Then
            caseNote.Note = Me.CommentsTextBox.Text
        Else
            caseNote.Note = "No comments entered by creator."
        End If

        caseNote.Persist(tran)
        tran.Commit()
    End Sub
End Class
